package com.pingtai.xinlang.login.login;

import java.io.FileWriter;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.List;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.select.Elements;
import org.w3c.dom.Entity;

import com.pingtai.xinlang.login.model.WeiboMsg;
import com.pingtai.xinlang.login.util.FileUtil;
import com.pingtai.xinlang.login.util.ParseFeed;

public class FeedUtils {
	private static final Log logger = LogFactory.getLog(FeedUtils.class);
	private static ParseFeed feed = new ParseFeed();
	private static FeedUtils utils = new FeedUtils();
	private static String MINE_UID = "1664639885";
	
	public String getHomeWeiboConent(HttpClient client, String personalUrl,String characet){
		String entity = getRawHtml(client, personalUrl,characet);
		return entity;
	}

	public List<WeiboMsg> getHomeWeiboMsgs(HttpClient client, String personalUrl) throws JSONException, IOException {
		// 第一次Get页面html，获取页数，最大id
		String entity = getRawHtml(client, personalUrl,"utf-8");
		FileWriter fw = new FileWriter("d:/xinlang.html");
		fw.write(entity);
		// FileUtil.saveToFile(entity, "home.html", "utf-8");
		String weiboFeedHtmlData = feed.getHomeNormalHTMLData(entity);
		// FileUtil.saveToFile(weiboFeedHtmlData, "home_weibo_feed.html",
		// "UTF-8");

		// 获取微博content elements
		Elements elements = feed.getWeiboContentElements(weiboFeedHtmlData);
		List<WeiboMsg> msgs = feed.parseHomeFeedFromElements(elements);

		long maxId = feed.getMaxWeiboId(weiboFeedHtmlData);

		// 首页数据只能获取10页，也就是150条
		for (int i = 2; i <= 10; i++) {
			String homeRequest = "http://weibo.com/aj/mblog/fsearch?_wv=5&page="
					+ i + "&count=15&max_id=" + maxId + "&pre_page=" + (i - 1);
			List<WeiboMsg> apiMsgs = parseWBMsgFromApiHtmlData(client,
					homeRequest, MINE_UID);
			msgs.addAll(apiMsgs);
		}
		return msgs;
	}

	/**
	 * 返回html response
	 * 
	 * @param client
	 * @param personalUrl
	 * @return
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	private String getRawHtml(HttpClient client, String personalUrl ,String characet) {
		HttpGet getMethod = new HttpGet(personalUrl);
		String entity = null;
		HttpResponse response = null;
		try {
			response = client.execute(getMethod);
			entity = EntityUtils.toString(response.getEntity(),characet);
		} catch (IOException e) {
			logger.error(e);
		}finally{
			HttpClientUtils.closeQuietly(response);
		}

		return entity;
	}

	private List<WeiboMsg> parseWBMsgFromApiHtmlData(HttpClient client,
			String apiUrl, String uid) {
		HttpGet getMethod;
		HttpResponse response;
		String weiboFeedHtmlData;
		Elements elements;
		List<WeiboMsg> apiMsgs = null;
		// 通过api的方式获取到首页微博信息
		getMethod = new HttpGet(apiUrl);
		try {
			response = client.execute(getMethod);
			weiboFeedHtmlData = EntityUtils.toString(response.getEntity());

			// 将得到的数据去除多余的字符格式化为json
			weiboFeedHtmlData = weiboFeedHtmlData.replace("\\/", "/");
			JSONObject jo = new JSONObject(weiboFeedHtmlData);

			// 获得微博html数据
			weiboFeedHtmlData = jo.getString("data");

			// 开始解析数据
			elements = feed.getWeiboContentElements(weiboFeedHtmlData);

			if ("1664639885".equals(uid)) {
				apiMsgs = feed.parseHomeFeedFromElements(elements);
			} else {
				apiMsgs = feed.parsePersonalWeibo(elements);
			}
		} catch (IOException e) {
			logger.error(e);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return apiMsgs;
	}

	/**
	 * 
	 * @param client
	 * @param personalUrl
	 * @param uid
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 * @throws JSONException
	 */
	public List<WeiboMsg> getPersonalPageWeibo(HttpClient client,
			String personalUrl, String uid) throws JSONException, IOException {
		// 第一次Get页面html，获取页数，最大id
		String entity = getRawHtml(client, personalUrl,"utf-8");
		// logger.info(entity);
		FileUtil.saveToFile(entity, "personal.html", "utf-8");

		String weiboFeedHtmlData = null;
		// 我自己的uid
		if ("1664639885".equals(uid)) {
			weiboFeedHtmlData = feed.getMyNormalHTMLData(entity);
		} else {
			weiboFeedHtmlData = feed.getOtherNormalHTMLData(entity);
		}

		FileUtil.saveToFile(weiboFeedHtmlData, "home_weibo_feed.html", "UTF-8");

		// 获取微博content elements
		Elements elements = feed.getWeiboContentElements(weiboFeedHtmlData);
		List<WeiboMsg> msgs = feed.parseHomeFeedFromElements(elements);

		long maxId = feed.getMaxWeiboId(weiboFeedHtmlData);
		int weiboCount = 0;
		try {
			weiboCount = feed.parseFeedCount(entity);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// 首页数据只能获取10页，也就是150条
		int pageCount = (weiboCount % 15 == 0) ? weiboCount / 15
				: weiboCount / 15 + 1;

		for (int i = 2; i <= pageCount - 1; i++) {
			String homeRequest = "http://weibo.com/aj/mblog/mbloglist?_wv=5&page="
					+ i
					+ "&count=15&max_id="
					+ maxId
					+ "&pre_page="
					+ (i - 1)
					+ "&uid=" + uid;
			List<WeiboMsg> apiMsgs = parseWBMsgFromApiHtmlData(client,
					homeRequest, uid);
			msgs.addAll(apiMsgs);
		}
		return msgs;
	}
}
